package com.example.openthedoor;

import com.baidu.aip.face.AipFace;
import com.example.openthedoor.decode.BASE64Encoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class FaceRepository {
    public static final String APP_ID = "24071324";
    public static final String API_KEY = "a2iOqBhGMSvZiKvyWSGnFkXo";
    public static final String SECRET_KEY = "RVpGjdU6fDBIikZOxxGUkeQkDzBBlnWR";
    public String feedback;
    AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
    private String imageType = "BASE64";
    private String groupId = "test0";
    private String userId = "";
    private String image = "";
    private String userInfo = "";


    public FaceRepository(HashMap<String, String> message) {
        if (message.containsKey("groupId")) this.groupId = message.get("groupId");
        if (message.containsKey("userInfo")) this.userInfo = message.get("userInfo");
        if (message.containsKey("image")) this.image = message.get("image");
        this.userId = message.get("userId");
    }

    public static String imageToBase64(String path) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(path);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }


    // 人脸注册
    public boolean enroll(String image) throws JSONException {
        String image64 = imageToBase64(image);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", userInfo);
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "APPEND");
        JSONObject res = client.addUser(image64, imageType, groupId, userId, options);
        System.out.println(res.toString(2));
        if (res.get("error_msg").equals("SUCCESS")) {
            feedback = "注册成功！";
            return true;
        } else if (res.get("error_msg").equals("face already exist")) {
            feedback = "账户已经存在！";
            return false;
        } else if (res.get("error_msg").equals("liveness check fail")) {
            feedback = "未检测到活体！";
            return false;
        } else {
            feedback = "其他错误！";
            return false;
        }
    }


    // 人脸更新
    public boolean update(String image) throws JSONException {
        String image64 = imageToBase64(image);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user's info");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("action_type", "REPLACE");
        JSONObject res = client.updateUser(image64, imageType, groupId, userId, options);
        if (res.get("error_msg").equals("SUCCESS")) {
            feedback = "更新成功！";
            return true;
        } else {
            feedback = "更新失败！";
            return false;
        }
    }

    public String search_face_token() throws JSONException {
        String face_token = "";
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        // 获取用户人脸列表
        JSONObject res = client.faceGetlist(userId, groupId, options);
        if (res.get("error_msg").equals("SUCCESS")) {
            JSONObject result = res.getJSONObject("result");
            JSONArray face_list_Array = result.getJSONArray("face_list");
            JSONObject temp_2 = face_list_Array.getJSONObject(0);
            face_token = temp_2.get("face_token").toString();
            return face_token;
        } else
            return null;
    }

    // 人脸删除
    public boolean delete() throws JSONException {
        // 初始化一个AipFace
        String faceToken = search_face_token();
        if (faceToken == null)
            return false;
        else {
            HashMap<String, String> options = new HashMap<String, String>();
            JSONObject res = client.faceDelete(userId, groupId, faceToken, options);
            System.out.println(res.toString(2));
            if (res.get("error_msg").equals("SUCCESS")) {
                feedback = "删除成功！";
                return true;
            } else {
                feedback = "删除成功！";
                return false;
            }
        }
    }
}
